package user

import (
	"github.com/labstack/echo"
	"strings"
	auth "tacitus/library/authorized"
	resp "tacitus/library/response"
)

func ShowHeadListHandler(c echo.Context) error {
	i := new(struct{
		Title string `json:"title"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	s := x.NewSession()
	for _, p := range strings.Split(i.Title, " ") {
		s.Where("title LIKE ?", "%"+p+"%")
	}
	data := make([]Head, 0)
	if err := s.Find(&data); err != nil {
		return err
	}
	return resp.List(c, data)
}

func SetUserHeadHandler(c echo.Context) error {
	uid := auth.CurrentUser(c).UserID
	i := new(struct{
		HeadID int64 `json:"head_id"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	if _, err := x.Where("id = ?", uid).Update(User{HeadID: i.HeadID}); err != nil {
		return err
	}
	return nil
}

func GetUserHeadHandler(c echo.Context) error {
	uid := auth.CurrentUser(c).UserID
	record, err := GetUserHead(uid)
	if err != nil {
		return err
	}
	return resp.Data(c, record)
}